<script setup lang="ts">
import { ICON_PREFIX } from '@/constants';
import { useDesign } from '@/hooks/useDesign';
import { propTypes } from '@/utils/propTypes';
import { ElIcon } from 'element-plus';
import { computed, unref } from 'vue';
import { Icon } from '@iconify/vue';

const prefixCls = useDesign().getPrefixCls('icon');
const props = defineProps({
  icon: propTypes.string,
  color: propTypes.string,
  size: propTypes.number.def(16),
  hoverColor: propTypes.string
});

const isLocal = computed(() => props.icon.startsWith('svg-icon:'));
const symbolId = computed(() => {
  return unref(isLocal) ? `#icon-${props.icon.split(':')[1]}` : props.icon;
});

const isUseOnlineIcon = computed(() => import.meta.env.VITE_USE_ONLINE_ICON === 'true');

const getIconifyStyle = computed(() => {
  const { color, size } = props;
  return {
    fontSize: `${size}px`,
    color
  };
});

const getIconName = computed(() => {
  return props.icon.startsWith(ICON_PREFIX) ? props.icon.replace(ICON_PREFIX, '') : props.icon;
});
</script>
<template>
  <ElIcon :class="prefixCls" :size="size" :color="color">
    <svg v-if="isLocal" aria-hidden="true">
      <use :xlink-href="symbolId" />
    </svg>
    <template v-else>
      <Icon v-if="isUseOnlineIcon" :icon="getIconName" :style="getIconifyStyle" />
      <div v-else :class="`${icon} iconify`" :style="getIconifyStyle" />
    </template>
  </ElIcon>
</template>
<style lang="less" scoped>
@prefix-cls: ~'@{adminNamespace}-icon';

.@{prefix-cls},
.iconify {
  :deep(svg) {
    &:hover {
      // stylelint-disable-next-line
      color: v-bind(hoverColor) !important;
    }
  }
}

.iconify {
  &:hover {
    // stylelint-disable-next-line
    color: v-bind(hoverColor) !important;
  }
}
</style>
